/**
 * Created by hama on 2016/6/12.
 */
var express = require('express');
var fs = require('fs');
var router = express.Router();

//读取文章的内容，返回给用户
router.get('/',function(req,res){
    function send(code,message,data){
        res.status(200).json({code,message,data});
    }
    function readFiles(i, files, questions, complete){
        if(i < files.length){
            fs.readFile(`questions/${files[i]}`, function(err,data) {
                if(!err){
                    questions.push(JSON.parse(data))
                }
                readFiles(++i, files, questions, complete)
            })
        }
        else{
            complete()
        }
    }
    fs.readdir('questions', (err, files) => {
        if(err){
            send('file error', '抱歉，系统错误...')
        }
        else{
            files = files.reverse()
            var questions = []

            readFiles(0, files, questions, function(){
                res.render('index', {
                    user: req.cookies.petname,
                    questions
                })
            })
        }
    })
})
module.exports = router